// 小仓库
import { defineStore } from 'pinia'
import { reqLogin,reqUserInfo,reqLogout } from '@/api/user'
import type { UserStatus } from './types/type'
import type { loginFormData,loginResponseData,userInfoResponseData } from '@/api/user/type'
// 引入本地存储的数据
import {SET_TOKEN,GET_TOKEN,REMOVE_TOKEN} from '@/utils/token'
// 常量路由
import { constantRoute } from "@/router/routes";
let useUserStore = defineStore('user', {
  //小仓库 存储数据
  state: (): UserStatus => {
    return {
    //   token: localStorage.getItem('TOKEN'),
      token:GET_TOKEN(),
      menuRouters:constantRoute,
      username:'',
      avatar:'',
    }
  },
  //异步|逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data)
      // console.log(result)
      if (result.code == 200) {
        //由于pinia|vuex存储数据其实利用js对象 不能持久化存储
        this.token = (result.data as string)
        //持久化存储
        // localStorage.setItem('TOKEN', result.data.token as string)
        SET_TOKEN(result.data as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息
    async userInfo(){
      let result:userInfoResponseData = await reqUserInfo()
      if(result.code == 200){
        this.username = result.data.name
        this.avatar = result.data.avatar
        return 'ok'
      }else{
        return Promise.reject(new Error(result.message))
      }
    },
    // 退出登录
    async userLogout(){
      let result:any = await reqLogout()
      if(result.code == 200){
      // 目前没有退出登录的接口 通知服务器本地用户唯一标识失效
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      }else{
        return Promise.reject(new Error(result.message))
      }
    }
  },
  getters: {},
})
export default useUserStore
